<template>
  <div class="tab-cart">
    <div class="editor_head" v-show="goods.length">
      <span class="float-l">我的购物车</span>
      <van-icon :name="isEditor ? 'success' : 'editor'" />
      <span @click="isEditor = !isEditor">{{isEditor ? '完成' : '编辑'}}</span>
    </div>

    <van-checkbox-group class="card-goods" v-model="checkedGoods">
      <van-cell v-for="(item, i) in goods" :key="i">
        <order-item :goods="item" :isEditor="isEditor" :stepperNum="item.total" @onNumChange="onNumChange(i, $event)" @onDel="deleteCart(i)" />
      </van-cell>

    </van-checkbox-group>
    <is-empty v-if="!goods.length">您的购物车空空如也~
      <div style="margin-top: 10px;">
        <van-button type="primary" plain @click="toHome">去逛逛吧</van-button>
      </div>
    </is-empty>

    <van-submit-bar style="bottom: 50px" :price="totalPrice" :disabled="!checkedGoods.length" :buttonText="submitBarText"
      :loading="isSubmit" label="合计：" @submit="cartSubmit">
      <van-checkbox v-model="checkedAll" @change="setCheckAll" style="padding: 0 10px;">全选</van-checkbox>
    </van-submit-bar>
  </div>
</template>

<script>
import {
  CheckboxGroup,
  Checkbox,
  SubmitBar,
} from "vant";

import {
  CART_EDIT,
  CART_DEL,
  CART_DELALL,
  CART_LIST
} from "@/api/shop";
import {
  GOODS_DETAIL
} from "@/api/goods";

import { IMAGE_PREFIX } from "@/api/goods";

import isEmpty from "@/vue/components/is-empty/";
import OrderItem from "./order-item";

export default {
  data() {
    return {
      isEditor: false,
      checkedAll: false,
      isSubmit: false,
      checkedGoods: [],
      goods: []
    };
  },

  activated() {
    this.checkedGoods = [];
    this.isEditor = false;
    this.$reqGet(CART_LIST, {memberId: this.user.id, centreId:this.user.centreId,limit: 0, offset: 0,time:new Date().getTime()})
      .then(res => {
        this.goods = res.data.data.rows;

        if (this.checkedAll) {
          this.setCheckAll(true);

        } else {
          this.checkedAll = true;
        }
      });

  },

  computed: {
    submitBarText() {
      const count = this.checkedGoods.length;
      return this.isEditor ? "删除" : "结算" + (count>0 ? `(${count})` : "");
    },
    totalPrice() {
      return this.goods.reduce(
        (total, item) =>
        total +
        (this.checkedGoods.indexOf(item.id) !== -1 ?
          item.marketprice * item.total * 100 :
          0),
        0
      );
    }
  },
  methods: {
    cartSubmit() {
      this.isSubmit = true;

      if (this.isEditor) {
        this.$dialog
          .confirm({
            message: "确定删除所选商品吗?",
            cancelButtonText: "再想想"
          })
          .then(() => {
            let itemsId = [];
            let total = 0;
            this.goods = this.goods.filter(
              goods => {
                  // console.log(goods);
                if (this.checkedGoods.indexOf(goods.id) == -1) {
                  return true;
                } else {
                  itemsId.push(goods.id);
                  total += goods.total;
                }
              }
            );
            this.checkedGoods = [];
            this.checkedAll = false;
            this.isEditor = !this.goods.length;
            this.$reqGet(CART_DELALL, {id: itemsId}).then(res => {
              this.changeCartNum(-total);
            });
            this.$nextTick(() => {
              this.isSubmit = false;
            });
          }).catch(() => {
            this.isSubmit = false;
          });
      } else {
        let items = [];
        this.goods.forEach(item => {
          if (this.checkedGoods.indexOf(item.id) !== -1) {
            items.push({
              cartId: item.id,
              productId: item.productId,
              total: item.total,
              skuId: item.skuId,
              skuTitle: item.skuTitle,
              marketprice: item.marketprice
            });
          }
        });

        this.$util.setSessionStorage("order", {cartItems: items, payback: {name: this.$route.name, params: this.$route.params}});
        //在我的购物车页面将 优惠券金额 存储到session里面
        this.$util.setSessionStorage("youhuiMon",0);
        this.isSubmit = false;
        this.$router.push({
          name: "placeOrderEntity"
        });
      }
    },
    formatPrice(price) {
      return (price / 100).toFixed(2);
    },
    setCheckAll(val) {
      this.checkedGoods = val ? this.goods.map(goods => goods.id) : [];
    },
    deleteCart(i) {
      this.isSubmit = true;

      this.$dialog
        .confirm({
          message: "确定删除所选商品吗",
          cancelButtonText: "再想想"
        })
        .then(() => {
          let item = this.goods[i];
          this.$reqPost(CART_DEL, {itemId: item.id}).then(res => {
            const total = (item.total === 0) ? 1 : item.total;
            this.changeCartNum(-total);
            this.goods.splice(i, 1);
            this.$nextTick(() => {
              this.deleteNext(item.id);
              this.isSubmit = false;
            });
          });
        }).catch(() => {
          this.isSubmit = false;
          let item = this.goods[i];

          if (item.total === 0) {
            item.total = 1;
          }
        });
    },
    deleteNext(goodsId) {
      if (this.goods.length === 0) {
        this.isEditor = false;
      }

      this.checkedGoods.forEach((goods, i) => {
        if (goods === goodsId) {
          this.checkedGoods.splice(i, 1);
          return false;
        }
      });
    },
    clearInvalid() {
      this.$dialog
        .confirm({
          message: "确定清除所有失效商品吗?",
          cancelButtonText: "再想想"
        })
        .then(() => {
          this.goods = this.goods.filter(goods => goods.status);
        });
    },
    onNumChange(index, num) {
      if (this.isSubmit) {
        return; //删除时会触发数量改变，这时不要响应
      }

      if (num === this.goods[index].total) {
        return;
      }

      if (num === 0) {
        this.goods[index].total = 0;
        this.deleteCart(index);
      } else {
        let item = this.goods[index];

        if (num < item.total) {
          this.submit(num, item);
        } else {
          if (!item.detail) {
            this.$reqGet(`${GOODS_DETAIL}`, {
              productId: item.productId
            }).then(res => {
              item.detail = res.data.data;
              this.submit(num, item);
            });
          } else {
              this.submit(num, item);
          }
        }
      }
    },
    toHome() {
      this.$router.push({ path: `/` });
    },
    submit(num, item) {
      if (item.detail && item.detail.maxbuy && (num > item.detail.maxbuy)) {
          this.$toast('已经超过单次购买数量');
          return;
      }

      this.$reqPost(CART_EDIT, {id: item.id, total: num}, {hideLoading: true}).then(res => {
        this.changeCartNum(num - item.total);
        item.total = num;
      });
    }
  },

  components: {
    [isEmpty.name]: isEmpty,
    [SubmitBar.name]: SubmitBar,
    [CheckboxGroup.name]: CheckboxGroup,
    [Checkbox.name]: Checkbox,
    [OrderItem.name]: OrderItem
  }
};
</script>

<style lang="scss" scoped>
@import "../../assets/scss/mixin";
.tab-cart {
  padding-bottom: 50px;
  box-sizing: border-box;
}
.editor_head {
  @include one-border;
  padding: 10px;
  font-size: $font-size-normal;
  background-color: $green;
  color: #fff;
  text-align: right;
}

.card-goods {
  background-color: $bg-color;
  margin-bottom: 70px;
}

.clear_invalid {
  width: 120px;
  color: $font-color-gray;
  border: 1px solid $font-color-gray;
  margin: 0 auto;
  text-align: center;
  padding: 5px 3px;
  margin-top: 20px;
  border-radius: 3px;
}
</style>
<style lang="scss">
  .van-submit-bar__bar {
      display: block;
      position: relative;
      .van-checkbox {
        position: absolute;
        height: 21px;
        top: 50%;
        transform: translateY(-50%);
      }
      .van-submit-bar__text {
        width: 100%;
        padding-left: 78px;
        padding-right: 123px;
        text-align: right;
        height: 60px;
        line-height: 60px;
        -webkit-box-flex:none;
        flex:none;
        box-sizing: border-box;
        -webkit-box-flex:none;
      }
      .van-button--danger {
        position: absolute;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
      }
    }
</style>
